import typeOfUtils from '@/utils/type-of-utils'
import listTreeUtils from '@/utils/listTree2List'
import { deepClone } from '@/utils/index'
import textUtils from '@/utils/textUtils'

const tableUtils = {
  /**
   * 表格重配置项里面获取校验规则,组成对象
   * 获取配置里面的editRender.rules
   * @param tableHead
   * @return {{}}
   */
  getEditDataTableEditRules(tableHead = []) {
    let result = {}
    if (typeOfUtils.isEmpty(tableHead)) {
      return result
    }
    tableHead.forEach(i => {
      if (i.editRender && i.editRender.rules) {
        result[i.prop] = i.editRender.rules
      }
      // eslint-disable-next-line no-prototype-builtins
      if (i.hasOwnProperty('children') && typeOfUtils.isNotEmpty(i.children)) {
        result = {
          ...this.getEditDataTableEditRules(i.children),
          ...result
        }
      }
    })
    return result
  },
  /**
   * 表头压平
   * @param tableHead
   * @param fontSize
   * @return {*[]}
   */
  tableHeadFlat(tableHead = [], fontSize = '12px') {
    const identifier = '_childrenIndex'
    tableHead = listTreeUtils.listTree2List(tableHead, false, 'children', identifier)
    const clone = deepClone(tableHead)
    tableHead = tableHead?.filter(i => { // 过滤掉所有有children的
      const find = clone?.findIndex(j => j[identifier] === i[identifier] + '-1')
      return find === -1;
    })?.map(i => { // 把父的标题给加在前面
      let isFristChildren = false
      if (i[identifier].endsWith('-1')) {
        isFristChildren = true
      }
      const parents = listTreeUtils.findParentByChildIndex(clone, i, true, identifier)
      parents?.push(i)
      const reduce = parents?.reduce((a, b) => {
        if (typeOfUtils.isEmpty(a)) {
          return b
        }
        const title = a.title + "-" + b.title
        if (isFristChildren) {
          return {
            ...a,
            ...b,
            title
          }
        } else {
          return {
            ...i,
            title
          }
        }
      }, {})
      return reduce
    })
    tableHead.forEach(i => {
      const getMinWidth = textUtils.visualLength(i.title, fontSize) + 16 * 2
      const minWidth = i.minWidth
      const width = parseFloat(minWidth)
      i.minWidth = width > getMinWidth ? width : getMinWidth
    })
    return tableHead
  }
  // 行转列
  // 列转行
}

export default tableUtils
